//
//  YMCardViewForVideo.m
//  VideoPic
//
//  Created by apple on 16/3/22.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "YMCardViewForVideo.h"
#import "YMVideoPlaySlider.h"
#import "YMVideoPlayer.h"
#import "YMModelForHotVideo.h"
#import "YSLDraggableCardContainer.h"
#import <YYWebImage.h>
#import "UILabel+Font.h"
#import "CheckDevice.h"
#import "YMHotDetailVC.h"
#import "HotViewController.h"

@interface YMCardViewForVideo ()<YMVideoPlayerDelegate>

@property (nonatomic, strong) UIView *playView;
@property (nonatomic, strong) UIButton *playButton;
@property (nonatomic, strong) YMVideoPlaySlider *slider;
@property (nonatomic, strong) YMVideoPlayer *player;
@property (nonatomic, strong) YMModelForHotVideo *model;
@property (nonatomic, strong) UILabel *labelForCurrent;
@property (nonatomic, strong) UILabel *labelForMax;
@property (nonatomic, strong) UIView *viewForBottom;
@property (nonatomic, strong) NSTimer *hidenTimer;
@property (nonatomic, strong) UIProgressView *progress;
@property (nonatomic, strong) UIImageView *imageViewForUserFace;
@property (nonatomic, strong) UILabel *labelOfUserName;
@property (nonatomic, strong) UILabel *labelOfHot;
@property (nonatomic, strong) UILabel *labelOfTitle;

@end


@implementation YMCardViewForVideo

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubViews];
        
        __weak typeof(self) weakSelf = self;
        [[NSNotificationCenter defaultCenter] addObserverForName:@"pauseAVPlayer" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
            if (weakSelf.player) {
                [weakSelf.player pause];
                weakSelf.playButton.hidden = NO;
                [UIView animateWithDuration:0.5 animations:^{
                    weakSelf.viewForBottom.alpha = 1;
                    weakSelf.progress.alpha = 0;
                }];
            }
        }];

    }
    return self;
}

- (void)passModel:(YMModelForHotVideo *)model {

    self.player.path = model.videoUrl;
    self.model = model;
    
    [self.imageViewForUserFace yy_setImageWithURL:[NSURL URLWithString:model.userFace] options:YYWebImageOptionProgressiveBlur |YYWebImageOptionSetImageWithFadeAnimation];
    
    self.labelOfUserName.text = model.userNick;
    self.labelOfTitle.text = model.videoTitle;
    //设置热度
    NSString *str = [NSString stringWithFormat:@"%@ 热度", model.vcntNice];
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:str];
    
    [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:[str rangeOfString:model.vcntNice]];
    
    [self.labelOfHot setAttributedText:attribute];
    
    
}

- (void)createSubViews {
    
    DeviceType phoneType = [CheckDevice getCurrentDevice];
    //创建播放图层
    self.playView = [[UIView alloc] init];
    if (phoneType != iPhoneThreePointFiveInch) {
        self.playView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.width);
    }else {
        self.playView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.width - 100);
    }
    
    
    [self addSubview:_playView];
    self.playView.backgroundColor = [UIColor blackColor];
    [self.player playInContainer:_playView];
    //暂停事件
    UITapGestureRecognizer *tapButton = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapAction)];
    [self.playView addGestureRecognizer:tapButton];
    
    //下方进度图层
    self.viewForBottom = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.playView.frame) - 30, self.frame.size.width, 30)];
    [self addSubview:_viewForBottom];
    
    UIBezierPath *backgroundPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 3, self.frame.size.width, 30)];
    
    self.viewForBottom.layer.shadowPath = backgroundPath.CGPath;
    self.viewForBottom.layer.shadowOpacity = 0.4;
    self.viewForBottom.layer.shadowRadius = 0;
    self.viewForBottom.layer.shadowColor = [UIColor blackColor].CGColor;
    
    
    //显示当前播放时间的label
    self.labelForCurrent = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 50, 30)];
    [self.viewForBottom addSubview:_labelForCurrent];
    self.labelForCurrent.text = @"00:00";
    self.labelForCurrent.font = [UIFont systemFontOfSize:15];
    self.labelForCurrent.textColor = [UIColor colorWithRed:0.702 green:0.702 blue:0.702 alpha:1.0];
    self.labelForCurrent.textAlignment = NSTextAlignmentRight;
    
    //显示视频时长的label
    self.labelForMax = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width - 50, 0, 50, 30)];
    [self.viewForBottom addSubview:_labelForMax];
    self.labelForMax.text = @"00:00";
    self.labelForMax.font = [UIFont systemFontOfSize:15];
    self.labelForMax.textColor = [UIColor colorWithRed:0.702 green:0.702 blue:0.702 alpha:1.0];

    
    //进度条
    self.slider = [[YMVideoPlaySlider alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.labelForCurrent.frame), 0, self.frame.size.width - 50 - 50, 30)];
    self.slider.thumbImage = [UIImage imageNamed:@"slider"];
    
    
    [self.slider addTarget:self action:@selector(playProgressChange:) forControlEvents:UIControlEventValueChanged];
    [self.slider addTarget:self action:@selector(playProgressChange:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchDragExit | UIControlEventTouchCancel];
    [self.slider addTarget:self action:@selector(handleSliderBegin:) forControlEvents:UIControlEventTouchDown];

    [self.viewForBottom addSubview:_slider];
    
    //播放按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playButton.frame = CGRectMake(0, 0, 50, 50);
    [self addSubview:_playButton];
    self.playButton.selected = YES;
    self.playButton.center = self.playView.center;
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateNormal];
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateSelected];
    self.playButton.userInteractionEnabled = NO;
    
    
    self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(0, self.playView.frame.size.height - 2, self.frame.size.width, 2)];
    [self.playView addSubview:_progress];
    self.progress.tintColor = [UIColor colorWithRed:1.0 green:0.8 blue:0.4 alpha:1.0];
    self.progress.trackTintColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.3];
    
    
    //下方内容图层
    UIView *viewOfContent = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.playView.frame), self.frame.size.width, self.frame.size.height - self.playView.frame.size.height)];
    [self addSubview:viewOfContent];
    
    //用户头像
    self.imageViewForUserFace = [[UIImageView alloc] initWithFrame:CGRectMake(20, viewOfContent.frame.size.height / 2 / 2, viewOfContent.frame.size.height / 2, viewOfContent.frame.size.height / 2)];
    [viewOfContent addSubview:_imageViewForUserFace];
    self.imageViewForUserFace.layer.cornerRadius =  viewOfContent.frame.size.height / 2 / 2;
    self.imageViewForUserFace.layer.masksToBounds = YES;
    self.imageViewForUserFace.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapForPush1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlePushVC:)];
    [self.imageViewForUserFace addGestureRecognizer:tapForPush1];
    
    //热门
    self.labelOfHot = [[UILabel alloc] initWithFrame:CGRectMake(viewOfContent.frame.size.width - 110, CGRectGetMinY(self.imageViewForUserFace.frame) + 5, 90, 20)];
    [viewOfContent addSubview:_labelOfHot];
    self.labelOfHot.textAlignment = NSTextAlignmentRight;
    self.labelOfHot.textColor = [UIColor grayColor];
    [self.labelOfHot handleFont:FontTypeSmall];
    self.labelOfHot.userInteractionEnabled = YES;

    UITapGestureRecognizer *tapForPush2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlePushVC:)];
    [self.labelOfHot addGestureRecognizer:tapForPush2];
    
    //用户名
    self.labelOfUserName = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.imageViewForUserFace.frame) + 10, CGRectGetMinY(self.imageViewForUserFace.frame) + 5, viewOfContent.frame.size.width - CGRectGetMaxX(self.imageViewForUserFace.frame) - 20 - 110, 20)];
    [viewOfContent addSubview:self.labelOfUserName];
    self.labelOfUserName.textColor = [UIColor grayColor];
    [self.labelOfUserName handleFont:FontTypeSmall];
    self.labelOfUserName.userInteractionEnabled = YES;

    UITapGestureRecognizer *tapForPush3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlePushVC:)];
    [self.labelOfUserName addGestureRecognizer:tapForPush3];
    
    //显示内容
    self.labelOfTitle = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.imageViewForUserFace.frame) + 10, CGRectGetMaxY(self.imageViewForUserFace.frame) - 20, viewOfContent.frame.size.width - CGRectGetMaxX(self.imageViewForUserFace.frame) - 30, 20)];
    [viewOfContent addSubview:_labelOfTitle];
    [self.labelOfTitle handleFont:FontTypeBig];
    self.labelOfTitle.userInteractionEnabled = YES;

    UITapGestureRecognizer *tapForPush4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlePushVC:)];
    [self.labelOfTitle addGestureRecognizer:tapForPush4];

}

- (void)handlePushVC:(UITapGestureRecognizer *)tap {
    YMHotDetailVC *detail = [[YMHotDetailVC alloc] init];
    detail.hidesBottomBarWhenPushed = YES;
    
    id object = [self nextResponder];
    while (![object isKindOfClass:[HotViewController class]] &&
           object != nil) {
        object = [object nextResponder];
    }
    
    HotViewController *hotVC = (HotViewController *)object;
    [hotVC.navigationController pushViewController:detail animated:YES];
    detail.model = self.model;
    [self.player pause];
    self.playButton.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        self.viewForBottom.alpha = 1;
        self.progress.alpha = 0;
    }];
    
}

- (void)handleSliderBegin:(YMVideoPlaySlider *)slider {
    id object = [self nextResponder];
    while (![object isKindOfClass:[YSLDraggableCardContainer class]] &&
           object != nil) {
        object = [object nextResponder];
    }
    
    YSLDraggableCardContainer *container = (YSLDraggableCardContainer *)object;
    container.gesture.enabled = NO;
}

- (void)playProgressChange:(YMVideoPlaySlider *)slider {
    [self.player moveTo:slider.value];
    self.progress.progress = slider.value;
    if (!self.playButton.selected) {
        [self.player play];
        id object = [self nextResponder];
        while (![object isKindOfClass:[YSLDraggableCardContainer class]] &&
               object != nil) {
            object = [object nextResponder];
        }
        
        YSLDraggableCardContainer *container = (YSLDraggableCardContainer *)object;
        container.gesture.enabled = YES;
    }
}

- (void)handleTapAction {
    self.playButton.selected = !self.playButton.selected;
    if (_playButton.selected) {
        [self.player pause];
        self.playButton.hidden = NO;
        [UIView animateWithDuration:0.5 animations:^{
            self.viewForBottom.alpha = 1;
            self.progress.alpha = 0;
        }];
        [self.hidenTimer invalidate];
    }
    else {
        [self.player play];
        self.playButton.hidden = YES;
    }
    
}

- (YMVideoPlayer *)player {
    if (_player == nil) {
        _player = [[YMVideoPlayer alloc] init];
        _player.delegate = self;
        __weak typeof(self) weakSelf = self;
        _player.bufferProgressBlock = ^(float f) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.slider.bufferValue = f;
            });
        };
        _player.progressBlock = ^(float f) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!weakSelf.slider.slide) {
                    weakSelf.slider.value = f;
                    weakSelf.progress.progress = f;
                }
            });
        };
        _player.currentTimeBlock = ^(float f) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.labelForCurrent.text = [weakSelf handleTime:f];
            });
        };
        _player.maxTimeBlock = ^(float f) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.labelForMax.text = [weakSelf handleTime:f];
            });
        };
    }
    return _player;
}

- (NSString *)handleTime:(float) f{
    int time = rint(f);
    NSString *timeStr = nil;
    if (time < 60) {
        timeStr = [NSString stringWithFormat:@"00:%02d", time];
    }else if (time < 3600){
        int minutes = time / 60;
        timeStr = [NSString stringWithFormat:@"%02d:%02d", minutes, time % 60];
    }else{
        int hours = time / 3600;
        int minutes = time / 60;
        timeStr = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, time % 60];
    }
    
    return timeStr;
}
#pragma mark - YMVideoPlayerDelegate

- (void)videoPlayerDidReadyPlay:(YMVideoPlayer *)videoPlayer {
//    [self.player play];
//    self.playButton.selected = YES;
//    self.playButton.hidden = NO;
    
}

- (void)videoPlayerDidBeginPlay:(YMVideoPlayer *)videoPlayer {
    [self.hidenTimer invalidate];
    self.hidenTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(handleHideBottom) userInfo:nil repeats:NO];
}

- (void)videoPlayerDidEndPlay:(YMVideoPlayer *)videoPlayer {
    [self.player playAtTheBeginning];
//    [self.player pause];
}

- (void)videoPlayerDidSwitchPlay:(YMVideoPlayer *)videoPlayer {
}

- (void)videoPlayerDidFailedPlay:(YMVideoPlayer *)videoPlayer {

}

- (void)handleHideBottom {
    [UIView animateWithDuration:0.5 animations:^{
        self.viewForBottom.alpha = 0;
        self.progress.alpha = 1;
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"pauseAVPlayer"];
    [_player clear];    
}

@end
